
package com.wjk.kylin.mall.gateway.config;

import com.wjk.kylin.mall.common.core.constant.Constants;
import com.wjk.kylin.mall.gateway.util.SysContext;
import feign.RequestInterceptor;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Feign相关配置类
 */
@Configuration
public class OpenFeignConfig {
    /**
     * 让DispatcherServlet向子线程传递RequestContext
     *
     * @param servlet servlet
     * @return 注册bean
     */
//    @Bean
//    public ServletRegistrationBean<DispatcherServlet> dispatcherRegistration(DispatcherServlet servlet) {
//        servlet.setThreadContextInheritable(true);
//        return new ServletRegistrationBean<>(servlet, "/**");
//    }

    /**
     * 覆写拦截器，在feign发送请求前取出原来的header并转发
     *
     * @return 拦截器
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return (template) -> {
            String traceID = SysContext.getTraceId();
            template.header(Constants.TRACE_ID_KEY, traceID);
            //打印日志携带traceId
            MDC.put(Constants.TRACE_ID_KEY, traceID);

//            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
//                    .getRequestAttributes();
//            assert attributes != null;
//            HttpServletRequest request = attributes.getRequest();
//            //获取请求头
//            Enumeration<String> headerNames = request.getHeaderNames();
//            if (headerNames != null) {
//                while (headerNames.hasMoreElements()) {
//                    String name = headerNames.nextElement();
//                    String values = request.getHeader(name);
//                    //将请求头保存到模板中
//                    template.header(name, values);
//                }
//            }
        };
    }
}

